<template>
  <!-- 顶部栏 -->
  <div class="top-bar">
    <h1>邻里社区积分商城</h1>
    <div class="points-info">
<!--      <span>我的积分: {{data.userPoints}}</span>-->
      <button @click="mypoints" class="points-task-btn">我的积分: {{data.user.points}}</button>
      <button @click="pointsplan" class="points-task-btn">积分任务</button>
    </div>
  </div>

  <!-- 商品筛选区 -->
  <div class="goods-filter">
    <h2>商品筛选</h2>
    <input
        v-model="data.searchQuery"
        type="text"
        placeholder="根据商品名搜索"
        class="search-input"
        @input="handleSearch"
    />
    <button @click="renovate">重置</button>
    <div class="filter-item">
      <label>商品分类</label>
      <select v-model="data.productsType" @change="handleSearch">
        <option value="0">所有类型</option>
        <option v-for="type in data.productsTypeList" :value="type.typeId">
          {{type.name}}
        </option>
      </select>
    </div>
    <div class="filter-item">
      <label>积分范围</label>
      <select v-model="data.pointsScope" @change="handleSearch">
        <option value="0">所有积分</option>
        <option :value="1">0-500积分</option>
        <option :value="2">500-1000积分</option>
        <option :value="3">高于1000积分</option>
      </select>
    </div>
    <div class="filter-item">
      <label>排序方式</label>
      <select v-model="data.pointsSort" @change="handleSearch">
        <option value="0">积分顺序</option>
        <option value="1">积分从低到高</option>
        <option value="2">积分从高到低</option>
      </select>
    </div>
  </div>
  <van-pull-refresh v-model="state.isRefresh" @refresh="onRefresh">
    <!-- 列表内容 -->
    <van-list
        v-model:loading="state.isLoading"
        :finished="state.finished"
        finished-text="没有更多了"

    >
      <van-grid :border="true" :column-num="2" class="grid">
        <van-grid-item v-for="item in productsList">
          <van-image @click="exchange(item.productId)" width="100" height="100" :src="item.images"/>
          <p style="margin-top: 5px">{{item.name}}</p>
          <div class="points-and-exchange">
            <p style="color: orange;margin-top: 2px">{{ item.pointsPrice }} 积分</p>
            <button @click="exchange(item.productId)" class="exchange-btn">兑换</button>
          </div>
        </van-grid-item>
      </van-grid>
    </van-list>
  </van-pull-refresh>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from '@/utils/axios.ts';
import { useRouter } from 'vue-router';

// localStorage.setItem("user_id", "0000000007");

// let userId = localStorage.getItem("user_id");

const router = useRouter();

// 这里只是为了模仿原有代码结构，若后续有动态加载需求可扩展
const productsList = ref([]);
const state = reactive({
  isRefresh: false,
  finished: false,
});
const renovate = () =>{
  location.reload();
}
const fetchProduct = () => {
  const params = {
    name: data.searchQuery,
    productsType: data.productsType,
    pointsSort: data.pointsSort,
    pointsScope: data.pointsScope
  }
  console.log("返回后端的搜索数据: ", params);
  axios.post("/api/mall/products/getProducts", params)
      .then(res => {
        console.log("查询响应数据: ", res.data);
        if (res.data != null){
          productsList.value = res.data;
        }
      })
}
const data = reactive({
  userPoints: 0,
  productsTypeList:'',
  productsType:0,
  pointsScope: 0,
  pointsSort:0,
  searchQuery:'',
  user: {
    userId: 0,
    phone: '',
    originalpwd: '',
    password: '',
    salt: '',
    repwdTimes: 0,
    nickname: '',
    avatar: '',
    building: '',
    unit: '',
    room: '',
    points: 0,
    createdAt: '',
    updatedAt: '',
    status: 0
  },
});
const handleSearch = () => {
  // // 重置分页
  // data.page = 1;
  // state.finished = false;
  // // 清空列表
  // productsList.value = [];
  fetchProduct();
}
onMounted(() => {
  // 若后续需要动态加载，可在这里调用初始化方法
  init();
});
const exchange = (productId)  => {
  console.log("商品id: ", productId);
  router.push({name: "pointMarketDetail", query: {pid: productId, uid:data.user.userId}});
}
const init = () => {
  axios.get(`/api/mall/products`)
      .then(res => {
        console.log("商品响应数据: ", res.data)
        productsList.value = res.data;
        state.isRefresh = false;
      });
  axios.post("/api/mallProductTypes/mallProductTypes")
      .then(res => {
        console.log("商品类型数据: ", res);
        data.productsTypeList = res.data;
      })
  // axios.get(`/api/users/getOneUsers/${userId}`)
  //     .then(res => {
  //       if (res.code == 200){
  //         console.log("用户数据: ", res.data);
  //         data.userPoints = res.data.points;
  //       }
  //     })
  axios.post("/api/users/getUserInfo")
      .then(res => {
        if (res.code == 200){
          console.log("响应的用户数据: ", res.data);
          data.user = res.data;
        }else {
          console.log("用户数据获取失败");
        }
      })
};

const onRefresh = () => {
  state.isRefresh = true;
  state.finished = false;
  // 若有刷新逻辑，可补充
  init();
};
const mypoints = () => {
  console.log("用户id: ", data.user.userId);
  router.push({name: "myPoints", query: {uid: data.user.userId}})
}
const pointsplan = () => {
  router.push({name: "pointsPlan", query: {uid: data.user.userId}})
}
</script>

<style scoped>
.top-bar {
  background-color: #673ab7;
  color: white;
  padding: 10px;
  text-align: center;
}

.points-info {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.points-task-btn {
  background-color: #5c6bc0;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 5px;
  margin-left: 10px;
  cursor: pointer;
}

.goods-filter {
  margin-top: 20px;
  background-color: #f9f9f9;
  padding: 15px;
}

.filter-item {
  margin-bottom: 10px;
}

label {
  display: block;
  margin-bottom: 5px;
}

select {
  width: 100%;
  padding: 5px;
  border-radius: 3px;
  border: 1px solid #ddd;
}

.goods-list {
  margin-top: 20px;
}

.goods-card {
  border: 1px solid #eee;
  padding: 15px;
  border-radius: 5px;
  position: relative;
}

.hot-tag {
  background-color: #f44336;
  color: white;
  padding: 3px 8px;
  border-radius: 3px;
  position: absolute;
  top: 10px;
  right: 10px;
}

.points-and-exchange {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.points-value {
  color: #d32f2f;
  font-weight: bold;
}

.exchange-btn {
  background-color: #42a5f5;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
}
</style>